var express = require('express');
var router = express.Router();

const { invokeGRTdown } = require('./grt-engine/index');

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with grt');
});

router.post('/vue3code', async (req, res, next) => {
  const resultDto = {
    code: 200,
    data: null,
    message: "success"
  }
  if (req.body && req.body.json) {
    const jsonDto = JSON.parse(req.body.json);
    // 判断是否上传了组件信息
    if (!jsonDto[0]) {
      resultDto.code = 601;
      resultDto.data = null;
      resultDto.message = "请上传组件json";
      res.send(resultDto);
    }

    const jsonObj = jsonDto[0].props;

    let type = ''; // 使用的模版类型
    if (jsonObj.templateType) {
      type = jsonObj.templateType;
    } else {
      type = '1';
    }

    // 校验模块名，空值打回
    if (!jsonObj.modelLabel) {
      resultDto.code = 601;
      resultDto.data = null;
      resultDto.message = "请上传模块名称";
      res.send(resultDto);
    }
    // 校验模块值，空值打回
    if (!jsonObj.modelName) {
      resultDto.code = 601;
      resultDto.data = null;
      resultDto.message = "请上传模块值";
      res.send(resultDto);
    }

    const modelName = await invokeGRTdown(jsonDto, type);
    const host = req.get('host');
    const filePath = `http://${host}/${modelName}`
    resultDto.code = 200;
    resultDto.data = filePath;
    resultDto.message = "success";
  } else {
    resultDto.code = 601;
    resultDto.data = null;
    resultDto.message = "请上传json数据";
  }
  res.send(resultDto);
});

module.exports = router;
